package com.chj.config;

import java.util.Random;

public class IdWorker {

	 // ==============================Fields===========================================
    /** 开始时间截 (2017-01-01) */
    private final long sosepoch = 1483200000000L;

    /** 机器id所占的位数 */
    private final long workerIdBits = 11L;
    
    /** 序列在id中占的位数 */
    private final long sequenceBits = 10L;

    /** 数据标识id所占的位数 */
    private final long datacenterIdBits = 2L;

    /** 支持的最大机器id，结果是2047 */
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);

    /** 支持的最大数据标识id，结果是3 */
    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);

    /** 机器ID向左移11位 */
    private final long workerIdShift = sequenceBits;

    /** 数据标识id向左移21位(10+11) */
    private final long datacenterIdShift = sequenceBits + workerIdBits;

    /** 时间截向左移23位(2+10+11) */
    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;

    /** 生成序列的掩码，这里为1023 */
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    /** 工作机器ID */
    private long workerId;

    /** 数据中心ID(0~3)    0:preProduction 1:GMC 2:SGM 3:keepBack*/  
    private long datacenterId;

    /** 毫秒内序列 */
    private long sequence = 0L;

    /** 上次生成ID的时间截 */
    private long lastTimestamp = -1L;

    public IdWorker() {
    	
    	String workerIdStr= System.getenv().get("SOSENVSEQID10");
    	
		if(workerIdStr!=null){
			workerId =Long.parseLong(workerIdStr.trim());
		}else{
			workerId = new Random().nextInt(-1 ^ (-1<< workerIdBits) );//  随机生成workerId (一般在preProduction发生)
		}
    	
    	
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        
        String dataCenterStr= System.getenv().get("SOSIDCSEQID10");
		
        if(dataCenterStr!=null){
        	datacenterId =Long.parseLong(dataCenterStr.trim());
		}else{
			datacenterId = 0;//default preProduction
		}
        
        
        if (datacenterId > maxDatacenterId || datacenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
        }
      
    }

    // ==============================Methods==========================================
    /**
     * 获得下一个ID (该方法是线程安全的)
     * @return SnowflakeId
     */
    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        //如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        sequence = (sequence + 1) & sequenceMask;

////////////********下方的原代码，全部注释，值保留上面一行，解决跨毫秒全为偶数问题********////////////
//        //如果是同一时间生成的，则进行毫秒内序列
//        if (lastTimestamp == timestamp) {
//            sequence = (sequence + 1) & sequenceMask;
//            //毫秒内序列溢出
//            if (sequence == 0) {
//                //阻塞到下一个毫秒,获得新的时间戳
//                timestamp = tilNextMillis(lastTimestamp);
//            }
//        }
//        //时间戳改变，毫秒内序列重置
//        else {
//            sequence = 0L;
//        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - sosepoch) << timestampLeftShift) 
                | (datacenterId << datacenterIdShift) 
                | (workerId << workerIdShift) 
                | sequence;
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }


    /** 测试 */
    public static void main(String[] args) {
    	
        IdWorker idWorker = new IdWorker();
        for (int i = 0; i < 10; i++) {
            long id = idWorker.nextId();
            System.out.println(Long.toBinaryString(id));
            System.out.println(id);
        }

    }
}
